package com.icebergteam.warfacewidget.core.asynctaskmanager;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;

public final class AsyncTaskManager implements IProgressTracker,
		OnCancelListener {
	private final ProgressDialog progressDialog;
	private final IProgressTracker progressTracker;
	private Task asyncTask;

	public AsyncTaskManager(Context context, IProgressTracker _progressTracker) {
		// Save reference to complete listener (activity)
		// Setup progress dialog
		progressDialog = new ProgressDialog(context);
		progressDialog.setIndeterminate(true);
		progressDialog.setOnCancelListener(this);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressTracker = _progressTracker;
	}

	public void setupTask(Task _asyncTask) {
		// Keep task
		asyncTask = _asyncTask;
		progressDialog.setCancelable(asyncTask.isCancelableTask());
		TaskProgress message = asyncTask.getProgressMessage();
		if (message != null) {
			onProgress(message);
		}
		// Wire task to tracker (this)
		asyncTask.setProgressTracker(this);
	}

	public ProgressDialog getProgressDialog() {
		return progressDialog;
	}
	
	/*callback IProgressTracker*/
	public void onProgress(final TaskProgress progress) {
		// Show dialog if it wasn't shown yet or was removed on configuration
		// // (rotation) change
		// // Show current message in progress dialog
		if (!progressDialog.isShowing()) {
			progressDialog.show();
		}
		progressDialog.setProgress(progress.progress);
		progressDialog.setMessage(progress.message);
	}

	/*callback oncancel*/
	public void onCancel(DialogInterface dialog) {
		// Cancel task
		asyncTask.cancel(true);
		// Reset task
		asyncTask = null;
	}

	public Object retainTask() {
		// Detach task from tracker (this) before retain
		if (asyncTask != null) {
			asyncTask.setProgressTracker(null);
		}
		// Retain task
		return asyncTask;
	}

	public void handleRetainedTask(Object instance) {
		// Restore retained task and attach it to tracker (this)
		if (instance instanceof Task) {
			setupTask((Task) instance);
		}
	}

	public boolean isWorking() {
		// Track current status
		return asyncTask != null;
	}

	public void dismissDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
		}
	}
	
	/*callback IProgressTracker*/
	@Override
	public void onComplete(String className, Object... params) {
		// Close progress dialog
		dismissDialog();
		// Reset task
		asyncTask = null;
		progressTracker.onComplete(className, params);
	}

	/*callback IProgressTracker*/
	@Override
	public void onCanceled(String className, Object... params) {
		// Close progress dialog
		progressTracker.onCanceled(className, params);
	}
}